﻿namespace Pibby.Core.Playlist
{
    using System;
    using System.IO;

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "u")]
	public static class M3uPlaylistReader
	{
		public static MediaPlaylist LoadFrom(TextReader reader)
		{
			const string m3uHeader = "#EXTM3U";
			const string extInfo = "#EXTINF:";

			if (reader == null)
				throw new ArgumentNullException("reader", Resources.Playlist_NullObjectError);

			var playlist = new MediaPlaylist();

			string line = string.Empty;

			bool headerRead = false;

			while ((line = reader.ReadLine()) != null)
			{
				if (line.StartsWith(m3uHeader))
				{
					headerRead = true;
				}
				else
				{
					if (headerRead)
					{
						if (!string.IsNullOrEmpty(line) && !line.StartsWith(extInfo))
						{
							playlist.Items.Add(new PlaylistItem(line));
						}
					}
				}
			}

			return playlist;
		}
	}
}
